package com.nhncorp.ntaf;

public class NtafIf extends NtafDoTraverse {

	public NtafIf(NtafExecuteData data) {
		super();
		this.flowFixture = data.getFlowFixture();
		this.data = data;
		this.data.initializeIfAttributes();
	}

	protected boolean checkPreConditions() {
		boolean result;

		//attribute "expr" is required. 
		if (data.getStrCondition().equals("")) {
			ntafInfo.printError("IF: EXPRESSION is required!");
			result = false;
		} else {
			result = true;
		}

		return result;
	}

	protected Object execute() {
		Object result = null;

		if (false == checkPreConditions()) {
			return null;
		}

		if (notSatisfyIfCondition()) {
			return null;
		}

		result = runInnerTables();

		return result;
	}

	protected boolean notSatisfyIfCondition() {
		boolean result;

		//check condition of attribute
		NtafFlowState state = data.getState();
		boolean bCondition = ntafInfo.checkCondition(data.getStrCondition());
		if (state.equals(NtafFlowState.IF)) {
			ntafInfo.removeIfConditionAll();
		}

		ntafInfo.setIfCondition(state, bCondition);

		if (state.equals(NtafFlowState.IF) && false == bCondition) {
			result = true;
		} else if (state.equals(NtafFlowState.ELSEIF)
			&& (false == bCondition || ntafInfo.getIfConditions().get(NtafFlowState.IF).equals(true))) {
			result = true;
		} else if (state.equals(NtafFlowState.ELSE) && isInvalidElseClause()) {
			result = true;
		} else {
			result = false;
		}

		return result;
	}

	protected boolean isInvalidElseClause() {
		boolean result = false;

		if (null != ntafInfo.getIfConditions().get(NtafFlowState.IF)) {
			if (null != ntafInfo.getIfConditions().get(NtafFlowState.ELSEIF)) {
				if ((ntafInfo.getIfConditions().get(NtafFlowState.IF).equals(true))
					|| (ntafInfo.getIfConditions().get(NtafFlowState.ELSEIF).equals(true))) {
					result = true;
				}
			} else {
				if ((ntafInfo.getIfConditions().get(NtafFlowState.IF).equals(true))) {
					result = true;
				}
			}
		} else {
			result = false;
		}

		return result;
	}
}